<script setup lang="ts">
import { onMounted, onUnmounted, ref, shallowRef } from 'vue'
import {
  AxesHelper,
  Scene,
  PerspectiveCamera,
  WebGLRenderer,
  TextureLoader,
  BufferGeometry,
  BufferAttribute,
  AdditiveBlending,
  Points,
  PointsMaterial,
  Color,
  HexColorString,
  ShaderMaterial,
} from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GUI } from 'dat.gui'
import Stats from 'three/examples/jsm/libs/stats.module'

import pointFrag from './plane.frag?raw'
import pointVert from './plane.vert?raw'

const contentRef = ref<HTMLCanvasElement>()
const renderer = shallowRef<WebGLRenderer>(new WebGLRenderer())
const orbitControls = shallowRef<OrbitControls>()
const scene = new Scene()
const camera = shallowRef<PerspectiveCamera>()
const axesHelper = new AxesHelper(20)
// 创建性能监视器
let stats = new Stats()

const gui = new GUI()

const init = () => {
  if (contentRef.value) {
    camera.value = new PerspectiveCamera(75, contentRef.value.clientWidth / contentRef.value.clientHeight)
    camera.value.position.set(0, 10, 10)
    scene.add(camera.value)
    scene.add(axesHelper)
    contentRef.value.appendChild(renderer.value.domElement)

    stats.dom.style.position = 'absolute'
    stats.dom.style.top = '0'
    stats.dom.style.left = '0'
    contentRef.value.appendChild(stats.dom)

    renderer.value.setSize(contentRef.value?.clientWidth, contentRef.value?.clientHeight)

    orbitControls.value = new OrbitControls(camera.value, renderer.value.domElement)
    orbitControls.value.enableDamping = true
  }
}

const render = () => {
  if (camera.value) {
    orbitControls.value?.update()
    renderer.value?.render(scene, camera.value)
  }
  stats.update()
  requestAnimationFrame(render)
}

window.addEventListener('resize', () => {
  if (contentRef.value && camera.value) {
    camera.value.aspect = contentRef.value.clientWidth / contentRef.value.clientHeight
    camera.value.updateProjectionMatrix()

    renderer.value.setSize(contentRef.value?.clientWidth, contentRef.value?.clientHeight)
    renderer.value.setPixelRatio(window.devicePixelRatio)
  }
})

onMounted(() => {
  init()

  const bufferGeometry = new BufferGeometry()
  const buffer = new Float32Array([0, 0, 0])
  bufferGeometry.setAttribute('position', new BufferAttribute(buffer, 3))

  const pointMaterial = new ShaderMaterial({
    vertexShader: pointVert,
    fragmentShader: pointFrag,
    transparent: true
  })

  const points = new Points(bufferGeometry, pointMaterial)
  scene.add(points)

  render()
})

onUnmounted(() => {
  gui.destroy()
})
</script>

<template>
  <div class="point-01" ref="contentRef"></div>
</template>

<style lang="scss" scoped>
.point-01 {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
